﻿namespace EventbriteApi.Model
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Xml.Linq;

    internal static class TimeZoneConverter
    {
        private static List<TimeZone> timeZones;

        static TimeZoneConverter()
        {
            var assembly = Assembly.GetExecutingAssembly();
            var manifestResource = string.Concat("EventbriteApi.Resources.TimeZones.xml");
            var stream = assembly.GetManifestResourceStream(manifestResource);
            var document = XDocument.Load(stream);

            timeZones = document.Descendants("timeZone").Select(t =>
                                  new TimeZone
                                  {                                     
                                      Name = (string)t.Attribute("Name"),
                                      GmtOffset = (string)t.Attribute("GmtOffset"),
                                  }).ToList();
        }

        public static DateTime GetDate(string dateString, string zoneName)
        {
            var gmtOffset = "";
            var timeZone = timeZones.FirstOrDefault(t => string.Equals(t.Name, zoneName, StringComparison.OrdinalIgnoreCase));                       

            if (timeZone != null)
            {
                gmtOffset = timeZone.GmtOffset;
            }

            return DateTime.Parse(dateString + gmtOffset);
        }

        private class TimeZone
        {
            public string Name { get; set; }

            public string GmtOffset { get; set; }
        }
    }
}
